<?php

namespace G4T\Form\Element;

class ManytooneElement extends \Zend_Form_Element_Select implements ElementInterface, TypeInterface
{
    private $entityName;
    private static $nameField = array('name', 'title');
    const ENTITY_NAMESPACE = "\\Catalog\\";

    public function init()
    {
        if (isset($this->entityName)) {
            $this->clearMultiOptions();
            $this->loadValues();
        }
    }

    private function loadValues()
    {
        $em = \Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('Doctrine')->getEntityManager();
        $entities = $em->getRepository($this->entityName)->findAll();
        if (!count($entities)) {
            return false;
        }
        $labelMethod = $this->getLabelMethodName($entities[0]);
        foreach ($entities as $entity) {
            if ($labelMethod) {
                $label = call_user_func(array($entity, $labelMethod));
                $this->addMultiOption($entity->getId(), $label);
            } else {
                $this->addMultiOption($entity->getId(), 'No label');
            }
        }

    }

    private function getLabelMethodName($entity)
    {
        foreach (self::$nameField as $field) {
            $methodName = 'get' . ucfirst($field);
            if (method_exists($entity, $methodName)) {
                return $methodName;
            }
        }
        return false;
    }

    public function setEntityName($entityName)
    {
        $this->entityName = $entityName;
        $this->init();
    }

    public function setParams(array $params)
    {
        $this->setEntityName(self::ENTITY_NAMESPACE . $params['targetEntity']);
    }

    /**
     * Текстовое название типа для jqgrid.
     *
     */
    public function getFormElementType()
    {
        return "select";
    }
}
